package com.gzlg.hospital.controller;

import com.github.pagehelper.PageInfo;
import com.gzlg.hospital.dao.PatientDao;
import com.gzlg.hospital.pojo.*;
import com.gzlg.hospital.pojo.query.hQuery;
import com.gzlg.hospital.service.DoctorService;
import jakarta.servlet.http.HttpSession;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.format.annotation.DateTimeFormat;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.time.ZoneId;
import java.util.*;
import java.util.stream.Collectors;

@Controller
public class DoctorController {
    @Autowired
    private DoctorService doctorService;
    //医生首页
    @GetMapping("/DoctorIndex")
    public String Doctor(HttpSession session) {
        Doctor doctor = (Doctor) session.getAttribute("user");
        return "Doctor/doctorIndex";
    }
    //个人信息
    @GetMapping("/Doctor/resume")
    public String DoctorResume(Integer id, Model model,HttpSession session) {
        Doctor doctor = (Doctor) session.getAttribute("user");
        model.addAttribute("doctor",doctorService.getDoctorById(doctor.getId()));
        return "Doctor/resume";
    }
    //待处理病历
    @GetMapping("/Doctor/appointmentDetails")
    public String listAppointmentDetailsByDoctorId(HttpSession  session, Model model,hQuery hQuery){
        Doctor doctor = (Doctor) session.getAttribute("user");
        model.addAttribute("page",doctorService.listAppointmentDetailsByDoctorId(doctor.getId(), hQuery));
        model.addAttribute("doctor",doctorService.getDoctorById(doctor.getId()));
        return "Doctor/appointment_details";
    }
    //根据挂号ID查处理病历
    @GetMapping("/Doctor/appointmentDetailsByRegistrationId")
    public String listAppointmentDetailsByIdDoctorId(HttpSession  session, Model model,@RequestParam Integer registration_id, hQuery hQuery) {
        Doctor doctor = (Doctor) session.getAttribute("user");
        Map<String, Integer> map = new HashMap<>();
        map.put("registration_id",registration_id);
        map.put("doctor_id",doctor.getId());
        model.addAttribute("page",doctorService.listAppointmentDetailsByRegistrationIdDoctorId(map, hQuery));
        model.addAttribute("doctor",doctorService.getDoctorById(doctor.getId()));
        return "Doctor/appointment_details";
    }
    @GetMapping("/Doctor/DoctorByStatus")
    public String DoctorByStatus(HttpSession session,Model model,@RequestParam String status,hQuery hQuery){
        Doctor doctor = (Doctor) session.getAttribute("user");
        model.addAttribute("page",doctorService.listAppointmentDetailsByDoctorId(doctor.getId(), hQuery));
        model.addAttribute("doctor",doctorService.getDoctorById(doctor.getId()));
        if(status.equals("处理中")){
            doctorService.DoctorByStatus1(doctor.getId());
            return "redirect:/Doctor/appointmentDetails";
        }else {
            doctorService.DoctorByStatus0(doctor.getId());
            return "redirect:/Doctor/appointmentDetails";
        }
    }
    //医生查看全部病历
    @GetMapping("/Doctor/medicalRecord")
    public String listMedicalRecord(HttpSession session, Model model,hQuery hquery) {
        Doctor doctor = (Doctor) session.getAttribute("user");
        if (doctor != null) {
            model.addAttribute("page",doctorService.listMedicalRecord(hquery));
            return "Doctor/medical_record";
        }else return "redirect:/login";
    }
    //医生查看指定患者病历
    @GetMapping("/Doctor/medicalRecordByPatientId")
    public String listMedicalRecordByPatientId(Model model,hQuery hquery, @RequestParam Integer patient_id) {
        model.addAttribute("page",doctorService.listMedicalRecordByPatientId(patient_id, hquery));
        return "Doctor/medical_record";
    }
    //护士查看待处理挂号
    @GetMapping("/Doctor/registration")
    public String listRegistration(HttpSession session, Model model,hQuery hQuery) {
        Doctor doctor = (Doctor) session.getAttribute("user");
        if (doctor != null) {
            model.addAttribute("page",doctorService.listRegistration(hQuery));
            return "Doctor/nurseRegistration";
        }else return "redirect:/login";
    }
    //护士处理挂号
    @GetMapping("/Doctor/gotoRegistration")
    public String gotoRegistration(
            Model model,
            @RequestParam(required = false) Integer registration_id,
            @RequestParam(required = false) Integer patient_id,
            @RequestParam(required = false) String department) {

        if (registration_id == null || patient_id == null) {
            return "redirect:/some-error-page";
        }

        try {
            Patient patient = doctorService.getPatientById(patient_id);
            Registration registration = doctorService.getRegistrationById(registration_id);

            model.addAttribute("patient", patient);
            model.addAttribute("registration", registration);
            model.addAttribute("department", department);

            // 不管用户是否选择了科室，都加载两个房间号列表
            List<Consultation_room> internalRooms = doctorService.getRoomsByDepartment("内科");
            List<Consultation_room> surgeryRooms = doctorService.getRoomsByDepartment("外科");// 使用迭代器安全地删除内科房间号列表中的元素
            // 使用迭代器安全地删除内科房间号列表中的元素
            Iterator<Consultation_room> internalIterator = internalRooms.iterator();
            while (internalIterator.hasNext()) {
                Consultation_room room = internalIterator.next();
                Doctor doctor = doctorService.getDoctorById(room.getDoctor_id());
                if (doctor.getStatus().equals("处理中") || !doctor.getDepartment().equals("内科")||!doctor.getRole().equals("DOCTOR")) {
                    internalIterator.remove();
                }
            }

// 使用迭代器安全地删除外科房间号列表中的元素
            Iterator<Consultation_room> surgeryIterator = surgeryRooms.iterator();
            while (surgeryIterator.hasNext()) {
                Consultation_room room = surgeryIterator.next();
                Doctor doctor = doctorService.getDoctorById(room.getDoctor_id());
                if (doctor.getStatus().equals("处理中") || !doctor.getDepartment().equals("外科")||!doctor.getRole().equals("DOCTOR")) {
                    surgeryIterator.remove();
                }
            }

// 将过滤后的列表传递给前端
            model.addAttribute("internalRooms", internalRooms);
            model.addAttribute("surgeryRooms", surgeryRooms);

        } catch (NumberFormatException e) {
            return "redirect:/some-error-page";
        }

        return "Doctor/nurseDepartment";
    }

    //护士开始处理挂号
    @PostMapping("/Doctor/updateRegistration")
    public String updateRegistration(
            RedirectAttributes redirectAttributes,
            @RequestParam Integer id,
            @RequestParam String department,
            @RequestParam(required = false) String remark,
            @RequestParam Integer patient_id,
            @RequestParam @DateTimeFormat(pattern = "yyyy-MM-dd'T'HH:mm") Date treatment_time,
            @RequestParam(required = false) String internal_room,
            @RequestParam(required = false) String surgery_room) {


        String treatment_room = department.equals("内科") ? internal_room : surgery_room;
        Integer doctor_id = doctorService.getConsultationRoomId(treatment_room);
        if (id == null || doctor_id == null || patient_id == null || treatment_room == null || treatment_room.isEmpty()) {
            redirectAttributes.addFlashAttribute("message", "请填写所有必填项");
            return "redirect:/Doctor/gotoRegistration?registration_id=" + id + "&patient_id=" + patient_id + "&department=" + department;
        }

        Appointment_details appointment_details = new Appointment_details();
        appointment_details.setRegistration_id(id);
        appointment_details.setPatient_id(patient_id);
        appointment_details.setDoctor_id(doctor_id);
        appointment_details.setRoom_number(treatment_room);
        appointment_details.setDoctor_name(doctorService.getDoctorById(doctor_id).getName());
        appointment_details.setTreatment_time(treatment_time);
        appointment_details.setCreate_date(new Date());
        appointment_details.setStatus("待处理");

        Map<String, Object> map = new HashMap<>();
        map.put("id", id);
        map.put("remark", remark);
        map.put("room", treatment_room);
        map.put("doctor_id", doctor_id);
        map.put("department", department);

        if (doctorService.updateRegistration(map)) {
            doctorService.addAppointmentDetails(appointment_details);
            redirectAttributes.addFlashAttribute("message", "处理成功");
        } else {
            redirectAttributes.addFlashAttribute("message", "处理失败");
        }

        redirectAttributes.addAttribute("registration_id", id);
        redirectAttributes.addAttribute("patient_id", patient_id);
        return "redirect:/Doctor/gotoRegistration";
    }

    @GetMapping("/Doctor/addMedicalRecord")
    public String  addMedicalRecord(Model model,@RequestParam Integer patient_id,@RequestParam Integer registration_id){
        Patient patient = doctorService.getPatientById(patient_id);
        Registration registration = doctorService.getRegistrationById(registration_id);
        model.addAttribute("patient",patient);
        model.addAttribute("registration",registration);
        return "Doctor/doappointment";
    }
    @PostMapping("/Doctor/addMedicalRecord")
    public String  addMedicalRecord(HttpSession session,
                                    @RequestParam String treatment_plan
                                    ,@RequestParam(required = false) LocalDateTime next_visit_date ,
                                    @RequestParam String diagnosis,
                                    @RequestParam Integer registration_id,
                                    @RequestParam Integer patient_id,
                                    RedirectAttributes redirectAttributes){
        Doctor doctor = (Doctor) session.getAttribute("user");
        Medical_record medical_record = new Medical_record();
        medical_record.setRegistration_id(registration_id);
        medical_record.setDiagnosis(diagnosis);
        medical_record.setDoctor_id(doctor.getId());
        medical_record.setTreatment_plan(treatment_plan);
        medical_record.setPatient_id(patient_id);
        if (next_visit_date != null){
            medical_record.setNext_visit_date(next_visit_date);
            if(doctorService.addMedicalRecord(medical_record)){
                doctorService.updateAppointmentDetails(registration_id);
                doctorService.updateRegistrationStatus(registration_id);
                redirectAttributes.addFlashAttribute("message","提交成功");
                return "redirect:/Doctor/addMedicalRecord?patient_id=" + patient_id + "&registration_id=" + registration_id;
            }else{
                redirectAttributes.addFlashAttribute("message","提交失败");
                return "redirect:/Doctor/addMedicalRecord?patient_id=" + patient_id + "&registration_id=" + registration_id;
            }
        }else {
            medical_record.setNext_visit_date(null);
            if(doctorService.addMedicalRecord2(medical_record)){
                doctorService.updateAppointmentDetails(registration_id);
                doctorService.updateRegistrationStatus(registration_id);
                redirectAttributes.addFlashAttribute("message","提交成功");
                return "redirect:/Doctor/addMedicalRecord?patient_id=" + patient_id + "&registration_id=" + registration_id;
            }else{
                redirectAttributes.addFlashAttribute("message","提交失败");
                return "redirect:/Doctor/addMedicalRecord?patient_id=" + patient_id + "&registration_id=" + registration_id;
            }
        }
    }
    @GetMapping("/Doctor/checkInSchedule")
    public String schedule(HttpSession session, Model model,hQuery hQuery) {
        Doctor doctor = (Doctor) session.getAttribute("user");
        PageInfo<Schedule> schedulePageInfo = doctorService.listScheduleByDoctorId(doctor.getId(), hQuery);
        model.addAttribute("page", schedulePageInfo);
        return "Doctor/ScheduleDoctor";
    }
    @GetMapping("/doctor/checkin")
    public String scheduleStatus(HttpSession session, Model model, hQuery hQuery,
                                 @RequestParam Integer scheduleId,
                                 @RequestParam String TimeButton,
                                 RedirectAttributes redirectAttributes) {

        Doctor doctor = (Doctor) session.getAttribute("user");
        if (doctor == null) {
            redirectAttributes.addFlashAttribute("message", "未登录或会话超时");
            return "redirect:/login";
        }

        PageInfo<Schedule> schedulePageInfo = doctorService.listScheduleByDoctorId(doctor.getId(), hQuery);
        model.addAttribute("page", schedulePageInfo);

        Schedule schedule = doctorService.getScheduleById(scheduleId);
        if (schedule == null) {
            redirectAttributes.addFlashAttribute("message", "排班信息不存在");
            return "redirect:/Doctor/checkInSchedule";
        }

        // 判断是否是今日排班
        if (!isSameDay(new Date(), schedule.getWork_date())) {
            redirectAttributes.addFlashAttribute("message", "只能对今日排班进行操作");
            return "redirect:/Doctor/checkInSchedule";
        }

        String shift = schedule.getShift();
        LocalTime nowTime = LocalTime.now();

        if ("checkInBtn".equals(TimeButton)) {
            Date startTime = schedule.getStartTime();
            if (startTime != null) {
                redirectAttributes.addFlashAttribute("message", "已打卡，请勿重复操作");
                return "redirect:/Doctor/checkInSchedule";
            }

            boolean isInTimeWindow = false;
            boolean isLate = false;
            LocalTime checkInStart = null;
            LocalTime checkInEnd = null;

            switch (shift) {
                case "全天班":
                    checkInStart = LocalTime.of(7, 50); // 7:50 开始可打卡
                    checkInEnd = LocalTime.of(8, 0);    // 8:00 结束正常打卡
                    break;
                case "上午班":
                    checkInStart = LocalTime.of(7, 50);
                    checkInEnd = LocalTime.of(8, 0);
                    break;
                case "下午班":
                    checkInStart = LocalTime.of(13, 50);
                    checkInEnd = LocalTime.of(14, 0);
                    break;
                default:
                    redirectAttributes.addFlashAttribute("message", "未知班次类型");
                    return "redirect:/Doctor/checkInSchedule";
            }

            // 判断当前时间是否在打卡时间窗口内
            isInTimeWindow = !nowTime.isBefore(checkInStart) && !nowTime.isAfter(checkInEnd);
            isLate = nowTime.isAfter(checkInEnd);

            if (isInTimeWindow) {
                if (doctorService.ScheduleStart(scheduleId)) {
                    redirectAttributes.addFlashAttribute("message", "打卡成功");
                } else {
                    redirectAttributes.addFlashAttribute("message", "打卡失败");
                }
            } else if (isLate) {
                if (doctorService.ScheduleStart(scheduleId)) {
                    redirectAttributes.addFlashAttribute("message", "你已迟到，打卡成功");
                } else {
                    redirectAttributes.addFlashAttribute("message", "打卡失败");
                }
            } else {
                // 当前时间早于打卡开始时间（如 7:49）
                redirectAttributes.addFlashAttribute("message", "尚未到打卡时间");
            }

        } else if ("checkOutBtn".equals(TimeButton)) {
            Date endTime = schedule.getEndTime();
            if (endTime != null) {
                redirectAttributes.addFlashAttribute("message", "已签退，请勿重复操作");
                return "redirect:/Doctor/checkInSchedule";
            }

            Date startTime = schedule.getStartTime();
            if (startTime == null) {
                redirectAttributes.addFlashAttribute("message", "请先打卡再签退");
                return "redirect:/Doctor/checkInSchedule";
            }

            boolean canCheckOut = false;
            LocalTime checkOutTimeLimit = null;

            switch (shift) {
                case "全天班":
                    checkOutTimeLimit = LocalTime.of(22, 0); // 晚上 10:00 后可签退
                    break;
                case "上午班":
                    checkOutTimeLimit = LocalTime.of(12, 0); // 中午 12:00 后可签退
                    break;
                case "下午班":
                    checkOutTimeLimit = LocalTime.of(22, 0); // 晚上 10:00 后可签退
                    break;
                default:
                    redirectAttributes.addFlashAttribute("message", "未知班次类型");
                    return "redirect:/Doctor/checkInSchedule";
            }

            canCheckOut = nowTime.isAfter(checkOutTimeLimit);

            if (canCheckOut) {
                if (doctorService.ScheduleEnd(scheduleId)) {
                    redirectAttributes.addFlashAttribute("message", "签退成功");
                } else {
                    redirectAttributes.addFlashAttribute("message", "签退失败");
                }
            } else {
                redirectAttributes.addFlashAttribute("message", "未到签退时间");
            }

        } else {
            redirectAttributes.addFlashAttribute("message", "无效操作");
        }

        return "redirect:/Doctor/checkInSchedule";
    }

    // 判断是否是同一天
    private boolean isSameDay(Date date, LocalDate localDate) {
        LocalDate localDate1 = date.toInstant().atZone(ZoneId.systemDefault()).toLocalDate();
        return localDate1.isEqual(localDate);
    }
    @GetMapping("/Doctor/DateSchedule")
    public String DateSchedule(HttpSession session,
                                @RequestParam String work_date,
                                Model model,hQuery hQuery) {
        Doctor  doctor=(Doctor) session.getAttribute("user");
        Map<String, Object> map = new HashMap<>();
        map.put("doctor_id", doctor.getId());
        map.put("work_date", work_date);
        PageInfo<Schedule> schedulePageInfo=doctorService.listScheduleByDate(map,hQuery);
        model.addAttribute("page",schedulePageInfo);
        return "Doctor/ScheduleDoctor";
    }
}